/*
 * @Author: lee
 * @Date: 2023-10-25 15:57:54
 * @LastEditors: lee
 * @LastEditTime: 2023-10-25 18:29:39
 * @Description: file content
 */
const mongoose = require('mongoose')
const config = require('../config/index')



const userSchema = mongoose.Schema({
	username: {
		type: String,
		default: ""
	}, //账号
	password: {
		type: String,
		required: true
	},
	email: {
		type: String,
		default: ""
	}, // 邮箱
	profile: {
		type: String,
		default: ""
	}, // 头像
	note: {
		type: String,
		default: "这个人很懒，啥都没有写"
	},
	// 权限
	auth: {
		type: String,
		default: 2
	},
	//粉丝
	followers: {
		type: [String],
		default: []
	},

	//是否关注了此人
	followered: {
		type: String
	}
}, {
	timestamps: {
		createdAt: 'created',
		updatedAt: 'updated'
	}
})


userSchema.methods.toAuthJSON = function(user) {
	return {
		id: this._id,
		username: this.username,
		email: this.email,
		phone: this.phone || '',
		profile: this.profile || `${config.SERVER_URL}/images/default_profile.png`,
		note: this.note,
		auth: this.auth || 2,
		followered: user ? this.isFollowed(user.id) : 0,
		followers: this.followers
	}
};


userSchema.methods.isFollowed = function(userId) {
	//判断当前登录用户是否是粉丝
	if (this.followers.includes(userId)) {
		return 1
	} else {
		return 0
	}
}

//添加关注
userSchema.methods.assertFollower = function(userId) {
	if (!this.followers.includes(userId)) {
		this.followers.push(userId)
		this.save();
	}

}
// 取消关注
userSchema.methods.unFollower = function(userId) {
	for (let i in this.favoritedList) {
		if (this.followers[i] === userId) {
			this.followers.splice(userId, 1)
			this.save()
		}
	}
}
const userModel = mongoose.model('Users', userSchema);

module.exports = {
	userModel
}
